<template>
  <div class="securityContent" :class="scroll.isFixed ? 'securityContentFixed' : ''" id="securityContent">
    <!-- 功能按钮 -->
    <div class="securityContent_button">
      <a-button class="addButton" type="primary" 
      :disabled="creatAble"
      @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
    </div>

    <!-- 表格展示部分 -->
    <baseTable
      :columns="columns.securityUserColumns"
      :dataSource="configData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="baseTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="configData.total"
      @deleteRecord="deleteSelectedAll"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'isDefault'">
          <a-switch
            size="small"
            @change="changeDefault(record)"
            v-model:checked="record.isDefault"
          />
        </template>
        <template v-if="column.dataIndex == 'contentSecrets'">
          {{record.contentSecrets ? record.contentSecrets.map((item: any) => item.name).join('、') : ''}}
        </template>
        <template v-if="column.dataIndex == 'enclosureSecrets'">
          {{record.enclosureSecrets ? record.enclosureSecrets.map((item: any) => item.name).join('、') : ''}}
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: editAble }" @click="eidtRecord(record)">{{ record.oparation[0] }}</a>
          <a-popconfirm
          :disabled="deleteAble"
            placement="topRight"
            ok-text="Yes"
            cancel-text="No"
            @confirm="confirmDelete(record)"
          >
            <template #title>
              <p style="width: 197px">
                删除后属于该人员密级的成员将移动至默认密级的分组中
              </p>
            </template>
            <a :class="{ disable: deleteAble }">{{ record.oparation[1] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length || deleteAble"
          >删除</a-button
        >
      </template>
    </baseTable>

    <!-- 新建人员密级模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      @handleOk="buttonMessage"
      @handleCancle="cancle"
      class="securitycontent_modal"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          autoComplete="off"
          class="ant-advanced-search-form"
          :model="formState"
          ref="contentFrom"
        >
          <a-form-item
            :name="['securityName', 'value']"
            :label="formState.securityName.label"
            :rules="[formState.securityName.rule]"
          >
            <a-input
              v-model:value="formState.securityName.value"
              show-count
              :maxlength="10"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :label="formState.securityContent.label"
            :name="['securityContent', 'value']"
            :rules="[formState.securityContent.rule]"
          >
            <a-select
            mode="multiple"
              v-model:value="formState.securityContent.value"
              @change="changeContent"
              placeholder="请选择"
              :options="contentOptions"
              :field-names="{ label: 'name', value: 'id' }"
            ></a-select>
          </a-form-item>
          <a-form-item
            :label="formState.securityEnclosure.label"
            :name="['securityEnclosure', 'value']"
            :rules="[formState.securityEnclosure.rule]"
          >
            <a-select
            mode="multiple"
              v-model:value="formState.securityEnclosure.value"
              @change="changeEnclosure"
              placeholder="请选择"
              :options="enclosureOptions"
              :field-names="{ label: 'name', value: 'id' }"
            ></a-select>
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { checkUserSequrity } from "./formRuler";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}

//data
const creatAble = ref<boolean>(false);
const editAble = ref<boolean>(false);
const deleteAble = ref<boolean>(false);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let datas = reactive<dataSourceType>({});
const baseTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
const contentOptions = ref([]);
const enclosureOptions = ref([]);
// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建密级",
});
const contentFrom = ref<any>("contentFrom");

const formState = reactive<dataSourceType>({
  securityName: {
    value: "",
    rule: {
      required: true,
      validator: checkUserSequrity,
      trigger: ["blur"],
      msg1: "密级名称不能为空！",
      msg2: "密级名称已存在！",
      api: "fetchUserSecretUnique",
      params: { id: "" },
    },
    label: "密级名称",
  },
  securityContent: {
    value: [],
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "内容密级不能为空！",
    },
    label: "内容密级",
  },
  securityEnclosure: {
    value: [],
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "附件密级不能为空！",
    },
    label: "附件密级",
  },
  id: "",
  contentSecretId: "",
  enclosureSecretId: "",
});
const contentId = ref(0);
const enclosureId = ref(0);
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
//methods
const addRecord = async () => {
  //新加tag词模态框条件修改
  //添加tag词数据
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建密级";
  formState.securityName.value = "";
  formState.securityContent.value = [];
  formState.securityEnclosure.value = [];

  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  if(editAble.value) return
  //编辑人员密级数据
  const data = await request.fetchUserSecret({ id: item.id });
  isAddOrEdit.value = true;
  modAlProps.title = "编辑密级";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  console.log(data,'data11')
  formState.securityName.value = data.name;
  formState.securityName.rule.params.id = data.id;
  formState.securityContent.value = data.contentSecretIds || [];
  formState.securityEnclosure.value = data.enclosureSecretIds || [];
  formState.enclosureSecretId = data.enclosureSecretId;
  formState.contentSecretId = data.contentSecretId;
  formState.id = item.id;
  isVisible.value = true;
};

const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑tag词调取接口
  //保存
  contentFrom.value
    .validate()
    .then(() => {
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
      const params = {
        id: type === "Edit" ? formState.id : null,
        name: formState.securityName.value,
        contentSecretIds: formState.securityContent.value,
        enclosureSecretIds: formState.securityEnclosure.value
      };
      request[type === "Edit" ? "fetchUserSecretUpdate" : "fetchUserSecretAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = msg.text == "保存" ? false : true;
    })
    .catch(() => {});
};

const cancle = () => {
  isVisible.value = false;
  contentFrom.value.resetFields()
};

const changeDefault = (record: any) => {
  //改变默认开关
  if (!record.isDefault) {
    Modal.confirm(
      Object.assign({}, msgModal.confirm, {
        title: "",
        content: "无法关闭，请至少设置一个默认人员密级",
        icon: createVNode("i", {
          class: "iconfont icon-warn warning_ICON",
        }),
        okText: "确定",
        onOk: () => {
          configData.records.forEach((item) => {
            if (item.id === record.id) {
              item.isDefault = true;
            }
          });
          Modal.destroyAll();
        },
        onCancel() {
          configData.records.forEach((item) => {
            if (item.id === record.id) {
              item.isDefault = true;
            }
          });
          Modal.destroyAll();
        },
      })
    );
  } else {
    let index = configData.records.findIndex((item) => item.isDefault);
    if (index !== -1) {
      Modal.confirm(
        Object.assign({}, msgModal.confirm, {
          title: "",
          content: `是否将人员密级 [${record.name}] 设置为默认密级？默认密级 有且只能存在一个`,
          icon: createVNode("i", {
            class: "iconfont icon-warn warning_ICON",
          }),
          okText: "确定",
          onOk: async () => {
            request
              .fetchUserSecretDefault({ id: record.id })
              .then((res: any) => {
                if (res.code == "00000 00000") {
                  configData.records.forEach((item) => {
                    if (item.id === record.id) {
                      item.isDefault = true;
                    } else {
                      item.isDefault = false;
                    }
                  });
                  message.success(res.message);
                } else {
                  message.error(res.message);
                }
              })
              .catch((err: any) => {
                throw new Error(err);
              });
            Modal.destroyAll();
          },
          onCancel() {
            configData.records.forEach((item) => {
              if (item.id === record.id) {
                item.isDefault = false;
              }
            });
            Modal.destroyAll();
          },
        })
      );
    }
  }
};

const confirmDelete = async (item: any) => {
  // 删除单个tag词
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

const deleteSelectedAll = async () => {
  //删除已选所有tag词
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的密级？删除后无法恢复",
      content: "删除后属于该人员密级的成员将移动至默认密级的分组中",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON ",
      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

const changeContent = (e: any, options: any) => {
  //获取内容id
  //formState.securityContent.value = e;
  //contentId.value = options.id;
};

const changeEnclosure = (e: any, options: any) => {
  //获取附件id
  // formState.securityEnclosure.value = e;
  // enclosureId.value = options.id;
};

const fetchUserSecretNameList = async () => {
  //获取密集名列表
  contentOptions.value = await request.fetchUserSecretNameList({ secretType: 1 });
  enclosureOptions.value = await request.fetchUserSecretNameList({ secretType: 2 });
  if (contentOptions.value.length) {
    contentOptions.value.forEach((item: any) => {
      item.value = item.name;
    });
  }
  if (enclosureOptions.value.length) {
    enclosureOptions.value.forEach((item: any) => {
      item.value = item.name;
    });
  }
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除tag词
  await request.fetchUserSecretDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRdecord();
    } else {
      message.error(res.message);
    }
  });
};

const getRdecord = async () => {
  // 获取表格数据
  const postData: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
  };
  const data = (await request.fetchUserSecretList(postData)) || {};
  let reqData = data;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records.map((item: any, index: number) => {
    sourceData = {
      ...item.middleDto,
      oparation: ["编辑", "删除"],
      num: index + 1,
      name: item.name,
      contentSecretName: item.contentSecretName,
      enclosureSecretName: item.enclosureSecretName,
      isDefault: item.isDefault,
      id: item.id,
      contentSecrets: item.contentSecrets,
      enclosureSecrets: item.enclosureSecrets,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  baseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "securityContent").y;
    scroll.isFixed = getTableScroll(74, "securityContent").isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getRdecord();
};

// computed
rowSelection = computed(() => {
  return baseTables.value.selectedRowKeys;
});
//onmounted
onMounted(() => {
  routerPerm().includes('creatAble') ? creatAble.value = false : creatAble.value = true;
  routerPerm().includes('editAble') ? editAble.value = false : editAble.value = true;
  routerPerm().includes('deleteAble') ? deleteAble.value = false : deleteAble.value = true;
  getRdecord();
  fetchUserSecretNameList();
});
</script>
<style lang="scss" scoped>

.securityContent {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  // overflow: hidden;

  .securityContent_button {
    padding-bottom: 16px;
    display: flex;
    .ant-btn {
      padding: 4px 16px 4px 12px;
    }
    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}
.securityContentFixed {
  width: 100%;
  height: calc(100% - 120px);
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
.model-tip {
  margin-top: 8px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
}

.tag-item {
  margin-bottom: 0 !important;
}

::v-deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-number) {
  width: 136px;
  margin-left: 4px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 506px;
  margin-left: 4px;
}
:deep(.ant-form-item-label > label) {
  justify-content: end;
  width: 80px;
}

::v-deep(.ant-form-item .ant-select, .ant-form-item .ant-cascader-picker) {
  width: 256px;
  margin-left: 4px;
}

::v-deep(.ant-form-item-with-help .ant-form-item-explain) {
  padding-left: 4px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
<style lang="less">
  .ant-modal-wrap {
    .ant-modal-confirm-title {
      font-size: 16px;
      font-weight: 600;
      line-height: 30px;
  }
}
</style>